import { Context, Next } from 'koa';
import { error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';
import { logToDatabase, LogType, LogLevel } from '../utils/logger';

/**
 * 错误处理中间件
 */
export async function errorHandlerMiddleware(ctx: Context, next: Next): Promise<void> {
  try {
    await next();
  } catch (err: any) {
    const requestId = ctx.state.requestId || 'unknown';
    const userId = ctx.state.user?.id;
    
    // 记录错误日志
    await logToDatabase(
      requestId,
      LogType.ERROR,
      LogLevel.ERROR,
      err.message || 'Unknown error',
      {
        stack: err.stack,
        name: err.name,
      },
      userId,
      ctx.ip,
      ctx.method,
      ctx.url
    );

    // 根据错误类型返回相应的响应码
    if (err.status) {
      error(ctx, err.status as ResponseCode, err.message);
    } else if (err.code) {
      error(ctx, err.code as ResponseCode, err.message);
    } else {
      error(ctx, ResponseCode.INTERNAL_SERVER_ERROR, err.message || '服务器内部错误');
    }
  }
}

